package com.gosophia.metadataEngine.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.json.annotations.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.gosophia.commons.web.action.BaseSupportAction;
import com.gosophia.metadataEngine.bean.TitleBean;
import com.gosophia.metadataEngine.bean.Values;
import com.gosophia.metadataEngine.dto.MetaDataFieldDto;
import com.gosophia.metadataEngine.ws.MetadataEngineWebService;
/**
 * 初始化列表项标题action
 * @author wangxinbing
 * @since 2011-05-10
 */
@Controller("InitMetaDataShowTitleItemAction")
@Scope("prototype")
public class InitMetaDataShowTitleItemAction extends BaseSupportAction{
    
	private Long metaDataTableId;
	
	private List<TitleBean> rows = new ArrayList<TitleBean>();
	
	private String title;
	
	@Autowired
	private MetadataEngineWebService metadataEngineWebService;
	
	@Override
	public String _execute() throws Exception {
		List<MetaDataFieldDto> showItems = metadataEngineWebService.findShowTitleItemsByTableId(metaDataTableId);
		for(MetaDataFieldDto dto : showItems){
			TitleBean titleBean = new TitleBean();
			titleBean.setTitle(dto.getFieldNameCN());
			titleBean.setName(dto.getPrivateName());
			titleBean.setSize("full");
			titleBean.setWidth(dto.getShowWidth());
			titleBean.setVtype(dto.getFieldType());
			titleBean.setUi("input");
			if("date".equalsIgnoreCase(dto.getFieldType())){
				titleBean.setUi("datepicker-range");
			}
			if("OUT_FK".equalsIgnoreCase(dto.getFieldType())){
				String name = "";
				MetaDataFieldDto refDto = metadataEngineWebService.findMetaDataFieldByDataFieldId(dto.getRefValue());
				name = dto.getPrivateName()+"."+refDto.getPrivateName();
				titleBean.setName(name);
				titleBean.setUi("select");
				titleBean.setVtype("string");
				List<List<Object>> values =  metadataEngineWebService.findRefValues(metaDataTableId,dto.getMetaDataFieldId());
				List<Values> vals = new ArrayList<Values>();
				for(List<Object> val : values){
					Values value = new Values();
					value.setTitle((String)val.get(0));
					value.setValue((String)val.get(0));
					vals.add(value);
				}
				titleBean.setVals(vals);
			}
			titleBean.setStaticContent(dto.getModelContent());
			rows.add(titleBean);
		}
		return SUCCESS;
	}
	public Long getMetaDataTableId() {
		return metaDataTableId;
	}
	public void setMetaDataTableId(Long metaDataTableId) {
		this.metaDataTableId = metaDataTableId;
	}
	@JSON
	public List<TitleBean> getRows() {
		return rows;
	}
	public void setRows(List<TitleBean> rows) {
		this.rows = rows;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
}
